package com.shuqi.model.net;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.shuqi.common.Config;
import com.shuqi.common.ConfigVersion;

/**
 * @des 描述 连网方式管理
 */

public class HttpFactory {

    public static int getApnType(Context m_context) {
        ConnectivityManager connMgr =
                (ConnectivityManager) m_context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connMgr == null)
            return NOT_EXIST;
        if (connMgr.getActiveNetworkInfo() == null)
            return NOT_EXIST;
        if (connMgr.getActiveNetworkInfo().isConnected()) {
            NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
            int type = activeInfo.getType();
            if (type == ConnectivityManager.TYPE_WIFI) {
                // wifi
                return WIFI_APN;
            } else if (type == ConnectivityManager.TYPE_MOBILE) {
                String extraInfo = activeInfo.getExtraInfo();
                if (extraInfo != null
                        && (extraInfo.equalsIgnoreCase("cmwap") || extraInfo
                                .equalsIgnoreCase("cmwap:gsm"))) {
                    return CMWAP_APN;
                }
                return CMNET_APN;
            }
        } else {
            return NOT_EXIST;
        }
        return DEFAULT_APN;
    }

    public static final int DEFAULT_APN = 0x0;

    public static final int CMWAP_APN = DEFAULT_APN + 1;

    public static final int CMNET_APN = DEFAULT_APN + 2;

    public static final int WIFI_APN = DEFAULT_APN + 3;

    public static final int NOT_EXIST = -1;

    /** 通过URL得到HttpURLConnection */
    public static HttpURLConnection getHttpURLConnectionFromURL(URL url, Context context)
            throws IOException, MalformedURLException {
        HttpURLConnection conn = null;
        if (Config.getNetType(context) != null// "ctwap".equals(Config.NET_TYPE)
                // ||
                && ("uniwap".equals(Config.getNetType(context))
                        || "cmwap".equals(Config.getNetType(context)) || "3gwap".equals(Config
                        .getNetType(context)))) {
            String host = url.getHost();
            String path = "http://10.0.0.172:80" + url.getFile();
            URL url2 = new URL(path);
            conn = (HttpURLConnection) url2.openConnection();
            conn.setRequestProperty("X-Online-Host", host);
            conn.setDoInput(true);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        if (conn != null) {
            conn.setRequestProperty("IP-SRC", "shuqi_" + Config.getNetType(context));
            conn.setRequestProperty("aak", ConfigVersion.getAppApiKey());
            conn.setRequestProperty("Accept-Encoding", "gzip");
        }
        return conn;
    }

    /** get方式通过urlStr 获取HttpGet */
    public static HttpGet getHttpGetFromUrlStr(String urlStr, Context context)
            throws MalformedURLException {

        HttpGet httpRequest = null;

        URL url = new URL(urlStr);
        if (Config.getNetType(context) != null
                && ("uniwap".equals(Config.getNetType(context))
                        || "cmwap".equals(Config.getNetType(context)) || "3gwap".equals(Config
                        .getNetType(context)))) {

            String host = url.getHost();
            String path = "http://10.0.0.172:80" + url.getFile();
            httpRequest = new HttpGet(path);
            httpRequest.setHeader("X-Online-Host", host);
        } else {
            httpRequest = new HttpGet(urlStr);
        }

        if (httpRequest != null) {
            httpRequest.setHeader("IP-SRC", "shuqi_" + Config.getNetType(context));
            httpRequest.setHeader("aak", ConfigVersion.getAppApiKey());
            httpRequest.setHeader("Accept-Encoding", "gzip");
        }
        return httpRequest;
    }

    /** post方式通过urlStr 获取HttpPost */
    public static HttpPost getHttpPostFromUrlStr(String urlStr, Context context)
            throws MalformedURLException {
        HttpPost httpRequest = null;

        URL url = new URL(urlStr);
        if (Config.getNetType(context) != null
                && ("uniwap".equals(Config.getNetType(context))
                        || "cmwap".equals(Config.getNetType(context)) || "3gwap".equals(Config
                        .getNetType(context)))) {
            String host = url.getHost();
            String path = "http://10.0.0.172:80" + url.getFile();
            httpRequest = new HttpPost(path);
            httpRequest.setHeader("X-Online-Host", host);
        } else {
            httpRequest = new HttpPost(urlStr);
        }

        if (httpRequest != null) {
            httpRequest.setHeader("IP-SRC", "shuqi_" + Config.getNetType(context));
            httpRequest.setHeader("aak", ConfigVersion.getAppApiKey());
            httpRequest.setHeader("Accept-Encoding", "gzip");
        }
        return httpRequest;
    }

    /** 将InputStream转换成byte[] */
    public static byte[] getBytes(InputStream is) throws IOException {
        if (is == null) {
            return null;
        }
        byte[] data = null;
        Collection<byte[]> chunks = new ArrayList<byte[]>();
        byte[] buffer = new byte[1024];
        int read = -1;
        int size = 0;
        while ((read = is.read(buffer)) != -1) {
            if (read > 0) {
                byte[] chunk = new byte[read];
                System.arraycopy(buffer, 0, chunk, 0, read);
                chunks.add(chunk);
                size += chunk.length;
            }
        }
        if (size > 0) {
            ByteArrayOutputStream bos = null;
            try {
                bos = new ByteArrayOutputStream(size);
                for (Iterator<byte[]> itr = chunks.iterator(); itr.hasNext();) {
                    byte[] chunk = itr.next();
                    bos.write(chunk);
                }
                data = bos.toByteArray();
            } finally {
                if (bos != null) {
                    bos.close();
                }
            }
        }
        return data;
    }
}
